<?php

namespace JyWxThird;

/**
 * Class Factory
 *
 * @method static \JyWxThird\Init\Application               Init(array $config)
 */
class WxThird
{
  public static function make($name, $config = [])
  {
    $namespace   = self::studly($name);
    $application = "\\JyWxThird\\{$namespace}\\Application";
    return new $application($config);
  }
  
  /**
   * Dynamically pass methods to the application.
   *
   * @param string $name
   * @param array  $arguments
   *
   * @return mixed
   */
  public static function __callStatic($name, $arguments)
  {
    return self::make($name, ...$arguments);
  }
  
  public static function studly($value)
  {
    $value = ucwords(str_replace(['-', '_'], ' ', $value));
    return str_replace(' ', '', $value);
  }
  
  /**
   * 解密数据
   *
   * @param string    $sessionKey
   * @param string    $encryptedData
   * @param string    $iv
   * @param int|array $errorCode
   * @return false|string
   */
  public static function decryptData($sessionKey, $encryptedData, $iv, &$errorCode = null)
  {
    if (strlen($sessionKey) != 24) {
      $errorCode = [
        'errCode' => -41001,
        'errMsg'  => 'sessionKey 长度有误，正常应为24',
      ];
      return false;
    } else if (strlen($iv) != 24) {
      $errorCode = [
        'errCode' => -41002,
        'errMsg'  => 'iv 长度有误，正常应为24',
      ];
      return false;
    }
    $aesKey    = base64_decode($sessionKey);
    $aesIV     = base64_decode($iv);
    $aesCipher = base64_decode($encryptedData);
    $result    = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
    $dataObj   = json_decode($result, true);
    if ($dataObj == null) {
      $errorCode = [
        'errCode' => -41003,
        'errMsg'  => '解密失败',
      ];
      return false;
    }
    return $dataObj;
  }
  
  /**
   * 解压xml
   * 将 `XML` 格式的数据转换成 `PHP` 的数组
   *
   * @param string $xml 要解压的xml
   * @return mixed
   */
  public static function deXml($xml)
  {
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  }
}
